#include <libqalculate/Calculator.h>
#include <libqalculate/ExpressionItem.h>
#include <libqalculate/Unit.h>
#include <libqalculate/Prefix.h>
#include <libqalculate/Variable.h>
#include <libqalculate/Function.h>

#include "qqcalc.h"

qqcalc::qqcalc(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	connect( ui.le_Input, SIGNAL( textChanged ( const QString &) ), this, SLOT( on_pb_Evaluate_clicked(const QString &) ) );

}

qqcalc::~qqcalc()
{

}

void qqcalc::on_pb_Evaluate_clicked(const QString & text)
{
    if ( ui.le_Input->text().isEmpty() )
    {
        ui.le_Input->setText("");
        return;
    }
    new Calculator();
    CALCULATOR->loadGlobalDefinitions();
    CALCULATOR->loadLocalDefinitions();
    CALCULATOR->loadGlobalCurrencies();
    CALCULATOR->loadExchangeRates();
    EvaluationOptions eo;

    eo.keep_zero_units = false;
    eo.parse_options.angle_unit = ANGLE_UNIT_DEGREES;

    switch (/*m_structuring*/0)
    {
        case 0:
            eo.structuring = STRUCTURING_NONE;
            break;
        case 1:
            eo.structuring = STRUCTURING_SIMPLIFY;
            break;
        case 2:
            eo.structuring = STRUCTURING_FACTORIZE;
            break;
    }

    QString input = ui.le_Input->text().replace(QChar(0xA3), "GBP").replace("$", "USD").replace(QChar(0x20AC), "EUR").replace("0b", "0b0").replace("(", " ( ").replace(")", " ) ");

    char* ctext = new char[input.size()+1];
    for (int i = 0; i < input.size(); i++)
        ctext[i] = input[i].toAscii();
    ctext[input.size()] = '\0';

    MathStructure result = CALCULATOR->calculate(ctext, eo);

    PrintOptions po;
    switch (/*m_fractionDisplay*/0)
    {
        case 0:
            po.number_fraction_format = FRACTION_DECIMAL;
            break;
        case 1:
            po.number_fraction_format = FRACTION_DECIMAL_EXACT;
            break;
        case 2:
            po.number_fraction_format = FRACTION_FRACTIONAL;
            break;
        case 3:
            po.number_fraction_format = FRACTION_COMBINED;
            break;
    }
    /*
    po.indicate_infinite_series = m_indicateInfiniteSeries;
    po.use_all_prefixes = m_useAllPrefixes;
    po.use_denominator_prefix = m_useDenominatorPrefix;
    po.negative_exponents = m_negativeExponents;
    */
    po.lower_case_e = true;
    result.format(po);

    QString res;

    po.base = 10;
    ui.lOutputDec->setText(/*res*/result.number().print(po).c_str());
    po.base = 16;
    ui.lOutputHex->setText(/*res*/result.number().print(po).c_str());
    po.base = 2;
    ui.lOutputBin->setText(/*res*/result.number().print(po).c_str());

/*
    m_history << m_input->text();

    if (m_history.size() > 0)
        m_historyIndex = m_history.size();

    if (m_copyToClipboard)
        QApplication::clipboard()->setText(result.print(po).c_str());
        */
}
